import base64
from loguru import logger
import requests
import cv2
import json
 
 
class MyEncoder(json.JSONEncoder):
	def default(self, obj):
		if isinstance(obj, bytes):
			return str(obj, encoding='utf-8')
		return json.JSONEncoder.default(self, obj)
 

def ali_ocr(base64_data):
    url ='http://10.12.14.120/tornado-cloud/imageSearch'
    param={
        'method':'ocrServiceProxy',
        'corp_id': '24338c6f0efd6c4bfb28f2ccbf9df6a4',
        'api_key': '977aad67-b719-4a1f-bbda-e71ce73862e6',
        'send_user': '1109008',
        'company': 'AUKS',
        'base64image': base64_data,
    }
    data = json.dumps(param,cls=MyEncoder)
    try:
        r = requests.post(url, data)
        json_object = json.loads(r.text)
        datas = json_object['ocrResult']['Data']['Results']
        new_datas = []
        for data in datas:
            new_data = {  
                'p': data['Probability'],  
                't': data['Text'],  
                'x': data['TextRectangles']['Left'],  
                'y': data['TextRectangles']['Top'],  
                'a': data['TextRectangles']['Angle'],  
                'h': data['TextRectangles']['Height'],  
                'w': data['TextRectangles']['Width']  
            }  
            new_datas.append(new_data)

        return new_datas 
    except Exception as e:
        logger.error(e)
        return None 

def image_to_base64(image_np):
    image = cv2.imencode('.jpg',image_np)[1]
    image_code = str(base64.b64encode(image))[2:-1]
    return image_code

def ocr_img_ali(np):
    return ali_ocr(image_to_base64(np))


   
    
        




